<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>员工列表</title>
    <%
        request.setAttribute("APP_PATH",request.getContextPath());
    %>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
    <link href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<!-- 新增员工 -->
<div class="modal fade" id="empAddModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">员工添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <input type="text" name="name" class="form-control" id="empName_add_input" placeholder="empName">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="text" name="email" class="form-control" id="email_add_input" placeholder="email@qq.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender1_add_input" checked="checked" value="男"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender2_add_input" value="女"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-4">
                            <select class="form-control" name="dId" id="dept_add_select"></select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
            </div>
        </div>
    </div>
</div>

<div class="container">
    <%-- 标题 --%>
    <div class="row">
        <div class="col-md-12">
            <h1>SSM-CRUD</h1>
        </div>
    </div>
    <%-- 按钮 --%>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button class="btn btn-success" id="emp_add_model_btn">新增</button>
            <button class="btn btn-danger">删除</button>
        </div>
    </div>
    <%-- 显示数据 --%>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover" id="emps_tables">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>empName</th>
                        <th>email</th>
                        <th>gender</th>
                        <th>deptName</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
        </div>
    </div>
    <%-- 显示分页信息 --%>
    <div class="row">
        <%-- 分页文字信息 --%>
        <div class="col-md-6" id="page_info_area"></div>

        <%-- 分页条 --%>
        <div class="col-md-6" id="page_nav_area"></div>
    </div>
</div>
    <script type="text/javascript">

        let totalNums;

        $(function () {
            to_page(1);
        });

        function to_page(pn) {
            $.ajax({
                url:"${APP_PATH}/emps",
                data:"pn=" + pn,
                type:"get",
                success:function (result) {
                    //console.log(result);
                    //解析并显示员工数据
                    build_emps_table(result);
                    //解析并显示分页信息
                    build_page_info(result);
                    build_page_nav(result);
                }
            });
        }
        
        //解析并显示员工数据
        function build_emps_table(result) {
            $("#emps_tables tbody").empty();
            let emps = result.extend.pageInfo.list;
            $.each(emps,function (index,item) {
                let empId = $("<td></td>").append(item.id);
                let empName = $("<td></td>").append(item.name);
                let empEmail = $("<td></td>").append(item.email);
                let empGender = $("<td></td>").append(item.gender);
                let empDeptName = $("<td></td>").append(item.dept.deptName);

                let editBtn = $("<button></button>").addClass("btn btn-success btn-sm")
                    .append($("<span></span>").addClass("glyphicon glyphicon-pencil"))
                    .append("编辑");
                let delBtn =  $("<button></button>").addClass("btn btn-danger btn-sm")
                    .append($("<span></span>").addClass("glyphicon glyphicon-trash"))
                    .append("删除");
                let btn = $("<td></td>").append(editBtn).append(" ").append(delBtn);

                $("<tr></tr>").append(empId).
                append(empName).
                append(empEmail).
                append(empGender).append(empDeptName).append(btn).appendTo("#emps_tables tbody");
            })
        }

        //解析并显示分页信息
        function build_page_info(result) {
            $("#page_info_area").empty();
            $("#page_info_area").append("当前第"+ result.extend.pageInfo.pageNum +" 页，总共"+result.extend.pageInfo.pages+" 页，总共"+result.extend.pageInfo.total+" 记录");
            totalNums = result.extend.pageInfo.total
        }

        //解析并显示分页信息
        function build_page_nav(result) {
            $("#page_nav_area").empty();
            let ul = $("<ul></ul>").addClass("pagination")

            let firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
            let prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;"));
            if (result.extend.pageInfo.hasPreviousPage == false){
                firstPageLi.addClass("disabled");
                prePageLi.addClass("disabled");
            }else {
                firstPageLi.click(function () {
                    to_page(1)
                });
                prePageLi.click(function () {
                    to_page(result.extend.pageInfo.pageNum-1)
                });
            }

            let nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;"));
            let lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href","#"));
            if (result.extend.pageInfo.hasNextPage == false){
                nextPageLi.addClass("disabled");
                lastPageLi.addClass("disabled");
            }else {
                lastPageLi.click(function () {
                    to_page(result.extend.pageInfo.pages);
                });
                nextPageLi.click(function () {
                    to_page(result.extend.pageInfo.pageNum+1)
                })
            }

            ul.append(firstPageLi).append(prePageLi);

            $.each(result.extend.pageInfo.navigatepageNums,function (index,item) {
                let numLi = $("<li></li>").append($("<a></a>").append(item));
                if (result.extend.pageInfo.pageNum == item){
                    numLi.addClass('active');
                }
                numLi.click(function () {
                    to_page(item);
                });
                ul.append(numLi);
            })

            ul.append(nextPageLi).append(lastPageLi);
            let navEle = $("<nav></nav>").append(ul);
            navEle.appendTo("#page_nav_area");
        }

        function reset_form(ele){
            $(ele)[0].reset();
            $(ele).find("*").removeClass("has-error has-success")
            $(ele).find(".help-block").text('')
        }

        $('#emp_add_model_btn').click(function () {
            reset_form("#empAddModel form")
            // $()[0].reset();
            getDepts();
            $('#empAddModel').modal();
        });

        //查出所有的部门信息
        function getDepts() {
            $("#dept_add_select").empty()
            $.ajax({
                url:"${APP_PATH}/depts",
                type: "get",
                success:function (result) {
                    $.each(result.extend.depts,function () {
                        let opetionEle = $("<option></option>").append(this.deptName).attr("value",this.deptId)
                        opetionEle.appendTo($("#dept_add_select"))
                    })
                }
            });
        }

        function show_validate_msg(ele,status,msg) {
            $(ele).parent().removeClass("has-success has-error ajax-va");
            $(ele).next("span").text("");
            if ("success" == status){
                $(ele).parent().addClass("has-success")
                $(ele).next("span").text(msg);
            }else if ("error" == status){
                $(ele).parent().addClass("has-error")
                $(ele).next("span").text(msg);
            }
        }
        
        //校验表单数据
        function validate_add_form(){
            let empName = $("#empName_add_input").val();
            let regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5}$)/;
            if (!regName.test(empName)){
                // alert("用户名可以是2-5位汉字或6-16位英语字母")
                show_validate_msg("#empName_add_input","error","用户名可以是2-5位汉字或6-16位英语字母")
                return false;
            }else {
                show_validate_msg("#empName_add_input","success","")
            }

            let email = $("#email_add_input").val()
            let regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
            if (!regEmail.test(email)){
                // alert("邮箱格式不正确")
                show_validate_msg("#email_add_input","error","邮箱格式不正确")
                return false
            }else {
                show_validate_msg("#email_add_input","success","")
            }
            return true
        }

        //检验用户名是否可用
        $("#empName_add_input").change(function () {
            let empName = this.value;
            $.ajax({
                url:"${APP_PATH}/checkuser",
                data:"empName=" + empName,
                type:"get",
                success:function (result) {
                    if (result.code == 100){
                        show_validate_msg("#empName_add_input","success","用户名可用")
                        $("#emp_save_btn").attr("ajax-va","success")
                    }else {
                        show_validate_msg("#empName_add_input","error",result.extend.va_msg)
                        $("#emp_save_btn").attr("ajax-va","error")
                    }
                }
            })
        })

        $("#emp_save_btn").click(function () {
            // alert($("#empAddModel form").serialize())
            if (!validate_add_form()){
                return false
            }
            // if (this.attr("ajax-va")=="error"){
            //     return false
            // }
            $.ajax({
                url:"${APP_PATH}/emp",
                type:"post",
                data:$("#empAddModel form").serialize(),
                success:function (result) {
                    // alert(result.msg)
                    $("#empAddModel").modal('hide')
                    to_page(totalNums)
                }
            })
        })


    </script>
</body>
</html>
